<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<meta name="theme-color" content="#222" media="(prefers-color-scheme: light)">
<meta name="theme-color" content="#222" media="(prefers-color-scheme: dark)"><meta name="generator" content="Hexo 6.3.0">
<link rel="preconnect" href="https://fonts.googleapis.com" crossorigin>
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">

<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,300italic,400,400italic,700,700italic%7CZCOOL+QingKe+HuangYou:300,300italic,400,400italic,700,700italic%7CNoto+Sans+Simplified+Chinese:300,300italic,400,400italic,700,700italic%7CJetBrains+Mono:300,300italic,400,400italic,700,700italic&display=swap&subset=latin,latin-ext">

<link rel="stylesheet" href="/lib/@fortawesome/fontawesome-free/css/all.min.css" integrity="sha256-HtsXJanqjKTc8vVQjO4YMhiqFoXkfBsjBWcX91T1jr8=" crossorigin="anonymous">
  <link rel="stylesheet" href="/lib/animate.css/animate.min.css" integrity="sha256-PR7ttpcvz8qrF57fur/yAx1qXMFJeJFiA6pSzWi0OIE=" crossorigin="anonymous">
  <link rel="stylesheet" href="/lib/@fancyapps/ui/dist/fancybox/fancybox.css" integrity="sha256-RvRHGSuWAxZpXKV9lLDt2e+rZ+btzn48Wp4ueS3NZKs=" crossorigin="anonymous">

<script class="next-config" data-name="main" type="application/json">{"hostname":"wyatex.online","root":"/","images":"/images","scheme":"Pisces","darkmode":true,"version":"8.18.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12},"copycode":{"enable":true,"style":"mac"},"fold":{"enable":false,"height":500},"bookmark":{"enable":false,"color":"#222","save":"auto"},"mediumzoom":false,"lazyload":true,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"stickytabs":false,"motion":{"enable":true,"async":true,"transition":{"menu_item":"fadeInDown","post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"搜索...","empty":"没有找到任何搜索结果：${query}","hits_time":"找到 ${hits} 个搜索结果（用时 ${time} 毫秒）","hits":"找到 ${hits} 个搜索结果"},"path":"/search.xml","localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":true}}</script><script src="/js/config.js"></script>

    <meta name="description" content="距离上次看qwik已经过去一年多的时间了，当时qwik才刚出没多久，那时候还是v0.1还是0.2的版本，还有很多bug就没兴趣研究了。如今过去一年多了，qwik版本已经到达了正式版，api也相对固定下来了，所有又有兴趣研究一下。 至于qwik是什么、对比别的框架有什么优势这里我就不重复提了，在掘金站内一搜一大堆。下面直接根据官方教程开始入门。这里推荐有一定的React基础（懂基本的jsx语法）、V">
<meta property="og:type" content="article">
<meta property="og:title" content="Qwik官方入门教程（1）">
<meta property="og:url" content="https://wyatex.online/%E5%89%8D%E7%AB%AF/QwikCourse-1/index.html">
<meta property="og:site_name" content="Wyatex&#96;s blog">
<meta property="og:description" content="距离上次看qwik已经过去一年多的时间了，当时qwik才刚出没多久，那时候还是v0.1还是0.2的版本，还有很多bug就没兴趣研究了。如今过去一年多了，qwik版本已经到达了正式版，api也相对固定下来了，所有又有兴趣研究一下。 至于qwik是什么、对比别的框架有什么优势这里我就不重复提了，在掘金站内一搜一大堆。下面直接根据官方教程开始入门。这里推荐有一定的React基础（懂基本的jsx语法）、V">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://wyatex.online/%E5%89%8D%E7%AB%AF/QwikCourse-1/p1.png">
<meta property="og:image" content="https://wyatex.online/%E5%89%8D%E7%AB%AF/QwikCourse-1/p2.png">
<meta property="og:image" content="https://wyatex.online/%E5%89%8D%E7%AB%AF/QwikCourse-1/p3.png">
<meta property="og:image" content="https://wyatex.online/%E5%89%8D%E7%AB%AF/QwikCourse-1/p4.png">
<meta property="og:image" content="https://wyatex.online/%E5%89%8D%E7%AB%AF/QwikCourse-1/p5.png">
<meta property="article:published_time" content="2023-10-28T15:33:07.000Z">
<meta property="article:modified_time" content="2023-12-05T11:39:20.164Z">
<meta property="article:author" content="Wyatex">
<meta property="article:tag" content="前端">
<meta property="article:tag" content="教程">
<meta property="article:tag" content="Qwik">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://wyatex.online/%E5%89%8D%E7%AB%AF/QwikCourse-1/p1.png">


<link rel="canonical" href="https://wyatex.online/%E5%89%8D%E7%AB%AF/QwikCourse-1/">



<script class="next-config" data-name="page" type="application/json">{"sidebar":"","isHome":false,"isPost":true,"lang":"zh-CN","comments":true,"permalink":"https://wyatex.online/%E5%89%8D%E7%AB%AF/QwikCourse-1/","path":"前端/QwikCourse-1/","title":"Qwik官方入门教程（1）"}</script>

<script class="next-config" data-name="calendar" type="application/json">""</script>
<title>Qwik官方入门教程（1） | Wyatex`s blog</title>
  








  <noscript>
    <link rel="stylesheet" href="/css/noscript.css">
  </noscript>
</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <div class="column">
      <header class="header" itemscope itemtype="http://schema.org/WPHeader"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <i class="logo-line"></i>
      <p class="site-title">Wyatex`s blog</p>
      <i class="logo-line"></i>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger" aria-label="搜索" role="button">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu"><li class="menu-item menu-item-home"><a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a></li><li class="menu-item menu-item-about"><a href="/about/" rel="section"><i class="fa fa-user fa-fw"></i>关于</a></li><li class="menu-item menu-item-tags"><a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签<span class="badge">97</span></a></li><li class="menu-item menu-item-categories"><a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类<span class="badge">26</span></a></li><li class="menu-item menu-item-archives"><a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档<span class="badge">155</span></a></li><li class="menu-item menu-item-编程"><a href="/programming/" rel="section"><i class="fa fa-book fa-fw"></i>编程</a></li><li class="menu-item menu-item-蹲坑读物"><a href="/%E5%B9%B2%E8%B4%A7/%E5%BC%80%E5%8F%91%E4%BA%A4%E6%B5%81%E7%BE%A4%E5%88%86%E4%BA%AB%E8%AE%B0%E5%BD%95/" rel="section"><i class="fa fa-book fa-fw"></i>蹲坑读物</a></li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup"><div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off" maxlength="80"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close" role="button">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div class="search-result-container no-result">
  <div class="search-result-icon">
    <i class="fa fa-spinner fa-pulse fa-5x"></i>
  </div>
</div>

    </div>
  </div>

</header>
        
  
  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%89%8D%E7%BD%AE%E6%9D%A1%E4%BB%B6"><span class="nav-number">1.</span> <span class="nav-text">前置条件</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E9%80%9A%E8%BF%87cli%E5%88%9B%E5%BB%BA%E4%B8%80%E4%B8%AAapp"><span class="nav-number">2.</span> <span class="nav-text">通过cli创建一个app</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E7%AE%80%E5%8D%95%E7%9A%84HelloWorld%E5%BA%94%E7%94%A8"><span class="nav-number">3.</span> <span class="nav-text">简单的HelloWorld应用</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%88%9B%E5%BB%BA%E4%B8%80%E4%B8%AA%E8%B7%AF%E7%94%B1"><span class="nav-number">3.1.</span> <span class="nav-text">创建一个路由</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%8A%A0%E8%BD%BD%E6%95%B0%E6%8D%AE"><span class="nav-number">3.2.</span> <span class="nav-text">加载数据</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%8F%90%E4%BA%A4%E6%95%B0%E6%8D%AE%E5%88%B0%E6%9C%8D%E5%8A%A1%E5%99%A8"><span class="nav-number">3.3.</span> <span class="nav-text">提交数据到服务器</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E4%BF%AE%E6%94%B9%E7%8A%B6%E6%80%81"><span class="nav-number">3.4.</span> <span class="nav-text">修改状态</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E7%9B%91%E5%90%AC%E7%8A%B6%E6%80%81%E5%8F%98%E5%8C%96%E5%B9%B6%E8%B0%83%E7%94%A8%E6%9C%8D%E5%8A%A1%E7%AB%AF%E5%87%BD%E6%95%B0"><span class="nav-number">3.5.</span> <span class="nav-text">监听状态变化并调用服务端函数</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#CSS%E6%A0%B7%E5%BC%8F"><span class="nav-number">3.6.</span> <span class="nav-text">CSS样式</span></a></li></ol></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="Wyatex"
      src="/images/avatar.jpg">
  <p class="site-author-name" itemprop="name">Wyatex</p>
  <div class="site-description" itemprop="description">这里是我用来做笔记的网站哟~</div>
</div>
<div class="site-state-wrap animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
        <a href="/archives/">
          <span class="site-state-item-count">155</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
          <a href="/categories/">
        <span class="site-state-item-count">26</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
          <a href="/tags/">
        <span class="site-state-item-count">97</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author animated">
      <span class="links-of-author-item">
        <a href="https://github.com/wyatex" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;wyatex" rel="noopener me" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="mailto:wyatex@qq.com" title="E-Mail → mailto:wyatex@qq.com" rel="noopener me" target="_blank"><i class="fa fa-envelope fa-fw"></i>E-Mail</a>
      </span>
  </div>

        </div>
      </div>
    </div>

    
    <div class="sidebar-inner sidebar-blogroll">
      <div class="links-of-blogroll animated">
        <div class="links-of-blogroll-title"><i class="fa fa-globe fa-fw"></i>
          链接
        </div>
        <ul class="links-of-blogroll-list">
            <li class="links-of-blogroll-item">
              <a href="https://antfu.me/" title="https:&#x2F;&#x2F;antfu.me&#x2F;" rel="noopener" target="_blank">Anthony Fu</a>
            </li>
            <li class="links-of-blogroll-item">
              <a href="https://www.codesky.me/" title="https:&#x2F;&#x2F;www.codesky.me&#x2F;" rel="noopener" target="_blank">CodeSky</a>
            </li>
            <li class="links-of-blogroll-item">
              <a href="https://learn.lianglianglee.com/" title="https:&#x2F;&#x2F;learn.lianglianglee.com&#x2F;" rel="noopener" target="_blank">技术文章摘抄</a>
            </li>
        </ul>
      </div>
    </div>
        <div class="pjax">
        <div class="sidebar-inner sidebar-post-related">
          <div class="animated">
              <div class="links-of-blogroll-title"><i class="fa fa-signs-post fa-fw"></i>
    相关文章
  </div>
  <ul class="popular-posts">
    <li class="popular-posts-item">
      <a class="popular-posts-link" href="/%E5%89%8D%E7%AB%AF/%E5%8A%A8%E6%80%81%E5%8A%A0%E8%BD%BDJS%E6%96%87%E4%BB%B6%E5%B9%B6%E6%89%A7%E8%A1%8C/" rel="bookmark">
        <time class="popular-posts-time">2022-10-12</time>
        <br>
      动态加载JS文件并执行
      </a>
    </li>
    <li class="popular-posts-item">
      <a class="popular-posts-link" href="/%E5%89%8D%E7%AB%AF/%E5%89%8D%E7%AB%AF%E6%89%93%E5%8C%85%EF%BC%9Atsup/" rel="bookmark">
        <time class="popular-posts-time">2022-06-13</time>
        <br>
      前端打包：tsup
      </a>
    </li>
    <li class="popular-posts-item">
      <a class="popular-posts-link" href="/Vue/Vue%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0%EF%BC%883%EF%BC%89%EF%BC%9A%E7%BB%84%E4%BB%B6%E5%9F%BA%E7%A1%80%E6%8B%93%E5%B1%95/" rel="bookmark">
        <time class="popular-posts-time">2021-06-28</time>
        <br>
      Vue学习笔记（3）：组件基础拓展
      </a>
    </li>
  </ul>

          </div>
        </div>
        </div>
  </aside>


    </div>

    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://wyatex.online/%E5%89%8D%E7%AB%AF/QwikCourse-1/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.jpg">
      <meta itemprop="name" content="Wyatex">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Wyatex`s blog">
      <meta itemprop="description" content="这里是我用来做笔记的网站哟~">
    </span>

    <span hidden itemprop="post" itemscope itemtype="http://schema.org/CreativeWork">
      <meta itemprop="name" content="Qwik官方入门教程（1） | Wyatex`s blog">
      <meta itemprop="description" content="">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          Qwik官方入门教程（1）
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>

      <time title="创建时间：2023-10-28 23:33:07" itemprop="dateCreated datePublished" datetime="2023-10-28T23:33:07+08:00">2023-10-28</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar-check"></i>
      </span>
      <span class="post-meta-item-text">更新于</span>
      <time title="修改时间：2023-12-05 19:39:20" itemprop="dateModified" datetime="2023-12-05T19:39:20+08:00">2023-12-05</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">分类于</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/%E5%89%8D%E7%AB%AF/" itemprop="url" rel="index"><span itemprop="name">前端</span></a>
        </span>
    </span>

  
    <span class="post-meta-item" title="阅读次数" id="busuanzi_container_page_pv">
      <span class="post-meta-item-icon">
        <i class="far fa-eye"></i>
      </span>
      <span class="post-meta-item-text">阅读次数：</span>
      <span id="busuanzi_value_page_pv"></span>
    </span>
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody"><p>距离上次看qwik已经过去一年多的时间了，当时qwik才刚出没多久，那时候还是v0.1还是0.2的版本，还有很多bug就没兴趣研究了。如今过去一年多了，qwik版本已经到达了正式版，api也相对固定下来了，所有又有兴趣研究一下。</p>
<p>至于qwik是什么、对比别的框架有什么优势这里我就不重复提了，在掘金站内一搜一大堆。下面直接根据官方教程开始入门。这里推荐有一定的React基础（懂基本的jsx语法）、Vue3响应式基础（会用ref、watch等）、TS基础的小伙伴观看。</p>
<p>官方入门原文：<a target="_blank" rel="noopener" href="https://qwik.builder.io/docs/getting-started/">https://qwik.builder.io/docs/getting-started/</a></p>
<span id="more"></span>

<h2 id="前置条件"><a href="#前置条件" class="headerlink" title="前置条件"></a>前置条件</h2><p>要在本地开始使用Qwik，你需要以下内容：</p>
<ul>
<li><a target="_blank" rel="noopener" href="https://nodejs.org/en/download/">Node.js v16.8</a> 或者更高</li>
<li>你喜欢的 IDE (推荐<a target="_blank" rel="noopener" href="https://code.visualstudio.com/">vscode</a>)</li>
<li>阅读 <a target="_blank" rel="noopener" href="https://qwik.builder.io/docs/concepts/think-qwik/">think qwik</a>（可选）</li>
</ul>
<p>国内网络环境的需要先设置sharp国内代理，不然可能安装依赖失败：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">npm config set sharp_binary_host &quot;https://npmmirror.com/mirrors/sharp&quot;</span><br><span class="line">npm config set sharp_libvips_binary_host &quot;https://npmmirror.com/mirrors/sharp-libvips&quot;</span><br></pre></td></tr></table></figure>

<h2 id="通过cli创建一个app"><a href="#通过cli创建一个app" class="headerlink" title="通过cli创建一个app"></a>通过cli创建一个app</h2><p>在你打算新建项目的路径，打开shell或者cmd，执行下面其中一个命令（按照你平时习惯选一个）：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">npm create qwik@latest</span><br><span class="line">pnpm create qwik@latest</span><br><span class="line">yarn create qwik</span><br><span class="line">bun create qwik@latest</span><br></pre></td></tr></table></figure>

<p>然后就会通过交互式的对话来创建项目，这里先全面选默认选项，一直下一步直到常见项目完成，会提示你cd到qwik-app文件夹，安装依赖，比如你用了pnpm创建，那么会提示你：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">cd qwik-app</span><br><span class="line">pnpm install</span><br><span class="line">pnpm start</span><br></pre></td></tr></table></figure>

<p>执行完start之后，会启动本地开发模式，这时候也会帮你打开网页，这样整个项目就创建好并启动了。</p>
<h2 id="简单的HelloWorld应用"><a href="#简单的HelloWorld应用" class="headerlink" title="简单的HelloWorld应用"></a>简单的HelloWorld应用</h2><p>这里先简单的在页面上显示HelloWorld，然后再从一言网址拉取一些名言或者网络流行句子进行展示。</p>
<h3 id="创建一个路由"><a href="#创建一个路由" class="headerlink" title="创建一个路由"></a>创建一个路由</h3><p>这一步要基于Qwik的元框架Qwik-city，他能根据项目的目录提供路由。</p>
<ol>
<li>在项目的<code>src/routes</code>目录下创建一个新的文件夹：<code>sentence</code>，并且在里面创建一个新文件 <code>index.tsx</code>.</li>
<li>每个路由下的<code>index.tsx</code>都需要包含：<code>export default component$(...)</code>，所以复制下面代码到上面新建的文件</li>
</ol>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// src/sentence/joke/index.tsx</span></span><br><span class="line"><span class="keyword">import</span> &#123; component$ &#125; <span class="keyword">from</span> <span class="string">&#x27;@builder.io/qwik&#x27;</span>;</span><br><span class="line"> </span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> <span class="title function_">component$</span>(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">  <span class="keyword">return</span> <span class="language-xml"><span class="tag">&lt;<span class="name">section</span> <span class="attr">class</span>=<span class="string">&quot;section bright&quot;</span>&gt;</span>Hello World!<span class="tag">&lt;/<span class="name">section</span>&gt;</span></span>;</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<ol start="3">
<li>在浏览器打开<a target="_blank" rel="noopener" href="http://127.0.0.1:5173/sentence/">http://127.0.0.1:5173/sentence/</a></li>
</ol>
<img data-src="/%E5%89%8D%E7%AB%AF/QwikCourse-1/p1.png" class="">

<blockquote>
<p>你的sentence路由组件现在被一个默认的布局包裹住，有关什么是布局以及如何使用布局的更多详细信息，请参阅<a target="_blank" rel="noopener" href="https://qwik.builder.io/docs/layout/">布局</a></p>
<p>有关如何编写组件的更多细节，请参阅<a target="_blank" rel="noopener" href="https://qwik.builder.io/docs/components/overview/">组件API部分</a>。</p>
</blockquote>
<h3 id="加载数据"><a href="#加载数据" class="headerlink" title="加载数据"></a>加载数据</h3><p>我们使用一言的api，从一言拉取一些句子。我们通过 <a target="_blank" rel="noopener" href="https://qwik.builder.io/docs/route-loader/">route loader</a> 在服务器拉取数据，然后在浏览器进行渲染。</p>
<p>将上面的<code>index.tsx</code>改成如下：</p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> &#123; component$ &#125; <span class="keyword">from</span> <span class="string">&#x27;@builder.io/qwik&#x27;</span>;</span><br><span class="line"><span class="keyword">import</span> &#123; routeLoader$ &#125; <span class="keyword">from</span> <span class="string">&#x27;@builder.io/qwik-city&#x27;</span>;</span><br><span class="line"> </span><br><span class="line"><span class="keyword">export</span> <span class="keyword">const</span> useHitokoto = <span class="title function_">routeLoader$</span>(<span class="keyword">async</span> () =&gt; &#123;</span><br><span class="line">  <span class="comment">// 去一言拉取数据</span></span><br><span class="line">  <span class="keyword">const</span> response = <span class="keyword">await</span> <span class="title function_">fetch</span>(<span class="string">&#x27;https://v1.hitokoto.cn/&#x27;</span>, &#123;</span><br><span class="line">    <span class="attr">headers</span>: &#123; <span class="title class_">Accept</span>: <span class="string">&#x27;application/json&#x27;</span> &#125;,</span><br><span class="line">  &#125;);</span><br><span class="line">  <span class="keyword">return</span> (<span class="keyword">await</span> response.<span class="title function_">json</span>()) <span class="keyword">as</span> &#123;</span><br><span class="line">    <span class="attr">id</span>: <span class="built_in">string</span>;</span><br><span class="line">    <span class="attr">hitokoto</span>: <span class="built_in">number</span>;</span><br><span class="line">    <span class="attr">from</span>: <span class="built_in">string</span>;</span><br><span class="line">  &#125;;</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> <span class="title function_">component$</span>(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">  <span class="comment">// 调用 `useHitokoto` 钩子, 会返回一个响应式信号量然后加载数据.</span></span><br><span class="line">  <span class="keyword">const</span> sentenceSignal = <span class="title function_">useHitokoto</span>();</span><br><span class="line">  <span class="keyword">return</span> (</span><br><span class="line">    <span class="language-xml"><span class="tag">&lt;<span class="name">section</span> <span class="attr">class</span>=<span class="string">&quot;section bright&quot;</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">      <span class="tag">&lt;<span class="name">p</span>&gt;</span>&#123;sentenceSignal.value.hitokoto&#125; --&#123;sentenceSignal.value.from&#125;<span class="tag">&lt;/<span class="name">p</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">    <span class="tag">&lt;/<span class="name">section</span>&gt;</span></span></span><br><span class="line">  );</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<p>保存代码之后再去浏览器查看：<a target="_blank" rel="noopener" href="http://127.0.0.1:5173/sentence/">http://127.0.0.1:5173/sentence/</a></p>
<img data-src="/%E5%89%8D%E7%AB%AF/QwikCourse-1/p2.png" class="">

<p>代码解析：</p>
<ul>
<li>通过<code>routeLoader$</code>调用的函数，都会在组件渲染前调用，然后渲染成html传到浏览器进行加载渲染。</li>
<li><code>routeLoader$</code>会返回一个use钩子（use-hook），比如上面可以通过<code>useHitokoto()</code>拿到服务器返回来的数据。</li>
</ul>
<blockquote>
<p><strong>注意</strong>：</p>
<p><code>routeLoader$</code>会在任何组件渲染前进行调用，也就是说，<code>export default component$(...)</code>里面就算不写<code>const sentenceSignal = useHitokoto();</code>，<code>routeLoader$</code>里的函数也会被调用。</p>
<p><code>routeLoader$</code>可以根据返回类型进行推导，所以下面的sentenceSignal能得到正确的类型，这也是为什么为什么要在return进行ts的<code>as</code>断言。</p>
</blockquote>
<h3 id="提交数据到服务器"><a href="#提交数据到服务器" class="headerlink" title="提交数据到服务器"></a>提交数据到服务器</h3><p>在前面，我们通过<code>routeLoader$</code>从服务器拉取数据，下面我们通过<a target="_blank" rel="noopener" href="https://qwik.builder.io/docs/action/"><code>routeAction$</code></a>从浏览器将数据发送到服务器。</p>
<blockquote>
<p>注意: <code>routeAction$</code>是向服务器发送数据的首选方式，因为它使用浏览器原生表单API，即使JavaScript被禁用也能正常工作。</p>
</blockquote>
<p>下面我们定义一个action，并且在组件用到这个action：</p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> &#123; component$ &#125; <span class="keyword">from</span> <span class="string">&#x27;@builder.io/qwik&#x27;</span>;</span><br><span class="line"><span class="keyword">import</span> &#123; routeLoader$, <span class="title class_">Form</span>, routeAction$ &#125; <span class="keyword">from</span> <span class="string">&#x27;@builder.io/qwik-city&#x27;</span>;</span><br><span class="line"> </span><br><span class="line"><span class="keyword">export</span> <span class="keyword">const</span> useHitokoto = <span class="title function_">routeLoader$</span>(<span class="keyword">async</span> () =&gt; &#123;</span><br><span class="line">  <span class="keyword">const</span> response = <span class="keyword">await</span> <span class="title function_">fetch</span>(<span class="string">&#x27;https://v1.hitokoto.cn/&#x27;</span>, &#123;</span><br><span class="line">    <span class="attr">headers</span>: &#123; <span class="title class_">Accept</span>: <span class="string">&#x27;application/json&#x27;</span> &#125;,</span><br><span class="line">  &#125;);</span><br><span class="line">  <span class="keyword">return</span> (<span class="keyword">await</span> response.<span class="title function_">json</span>()) <span class="keyword">as</span> &#123;</span><br><span class="line">    <span class="attr">id</span>: <span class="built_in">string</span>;</span><br><span class="line">    <span class="attr">hitokoto</span>: <span class="built_in">number</span>;</span><br><span class="line">    <span class="attr">from</span>: <span class="built_in">string</span>;</span><br><span class="line">  &#125;;</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">const</span> useSentenceVoteAction = <span class="title function_">routeAction$</span>(<span class="function">(<span class="params">props</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;投票&#x27;</span>, props)</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> <span class="title function_">component$</span>(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">  <span class="comment">// 调用 `useHitokoto` 钩子, 会返回一个响应式信号量然后加载数据.</span></span><br><span class="line">  <span class="keyword">const</span> sentenceSignal = <span class="title function_">useHitokoto</span>();</span><br><span class="line">  <span class="keyword">const</span> favoriteSentenceAction = <span class="title function_">useSentenceVoteAction</span>();</span><br><span class="line">  <span class="keyword">return</span> (</span><br><span class="line">    <span class="language-xml"><span class="tag">&lt;<span class="name">section</span> <span class="attr">class</span>=<span class="string">&quot;section bright&quot;</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">      <span class="tag">&lt;<span class="name">p</span>&gt;</span>&#123;sentenceSignal.value.hitokoto&#125; ——&#123;sentenceSignal.value.from&#125;<span class="tag">&lt;/<span class="name">p</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">      <span class="tag">&lt;<span class="name">Form</span> <span class="attr">action</span>=<span class="string">&#123;favoriteSentenceAction&#125;</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">        <span class="tag">&lt;<span class="name">input</span> <span class="attr">type</span>=<span class="string">&quot;hidden&quot;</span> <span class="attr">name</span>=<span class="string">&quot;id&quot;</span> <span class="attr">value</span>=<span class="string">&#123;sentenceSignal.value.id&#125;</span> /&gt;</span></span></span><br><span class="line"><span class="language-xml">        <span class="tag">&lt;<span class="name">input</span> <span class="attr">type</span>=<span class="string">&quot;hidden&quot;</span> <span class="attr">name</span>=<span class="string">&quot;sentence&quot;</span> <span class="attr">value</span>=<span class="string">&#123;sentenceSignal.value.hitokoto&#125;</span> /&gt;</span></span></span><br><span class="line"><span class="language-xml">        <span class="tag">&lt;<span class="name">button</span> <span class="attr">name</span>=<span class="string">&quot;vote&quot;</span> <span class="attr">value</span>=<span class="string">&quot;up&quot;</span>&gt;</span>👍<span class="tag">&lt;/<span class="name">button</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">        <span class="tag">&lt;<span class="name">button</span> <span class="attr">name</span>=<span class="string">&quot;vote&quot;</span> <span class="attr">value</span>=<span class="string">&quot;down&quot;</span>&gt;</span>👎<span class="tag">&lt;/<span class="name">button</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">      <span class="tag">&lt;/<span class="name">Form</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">    <span class="tag">&lt;/<span class="name">section</span>&gt;</span></span></span><br><span class="line">  );</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<p>保存代码，页面多出两个按钮，随便点一个，再查看服务端有没有打印：</p>
<img data-src="/%E5%89%8D%E7%AB%AF/QwikCourse-1/p3.png" class="">

<p>代码解析：</p>
<ul>
<li><code>routeAction$</code> 接收数据.<ul>
<li>传递给<code>routeAction$</code>的函数在发送表单时就会在服务器上调用。</li>
<li><code>routeAction$</code>返回一个use-hook, favoriteSentenceAction，你可以在组件中使用它来发送表单数据。</li>
</ul>
</li>
<li>Form是一个方便的组件，它封装了浏览器的原生<code>&lt;form&gt;</code>元素</li>
</ul>
<h3 id="修改状态"><a href="#修改状态" class="headerlink" title="修改状态"></a>修改状态</h3><p>类似Vue3的ref，Qwik提供了一个hook：<code>useSignal</code>，用来保存状态，并且提供响应式。下面来使用一下：</p>
<ol>
<li>从 <code>qwik</code> 导入 <code>useSignal</code>：<code>import &#123; component$, useSignal &#125; from &quot;@builder.io/qwik&quot;;</code></li>
<li>在组件定义里面定义这个signal：<code>const isFavoriteSignal = useSignal(false);</code></li>
<li>在Form的关闭标签后面添加一个按钮，用于修改状态</li>
</ol>
<p>最终代码变成：</p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> &#123; component$, useSignal &#125; <span class="keyword">from</span> <span class="string">&#x27;@builder.io/qwik&#x27;</span>;</span><br><span class="line"><span class="keyword">import</span> &#123; routeLoader$, <span class="title class_">Form</span>, routeAction$ &#125; <span class="keyword">from</span> <span class="string">&#x27;@builder.io/qwik-city&#x27;</span>;</span><br><span class="line"> </span><br><span class="line"><span class="keyword">export</span> <span class="keyword">const</span> useHitokoto = <span class="title function_">routeLoader$</span>(<span class="keyword">async</span> () =&gt; &#123;</span><br><span class="line">  <span class="keyword">const</span> response = <span class="keyword">await</span> <span class="title function_">fetch</span>(<span class="string">&#x27;https://v1.hitokoto.cn/&#x27;</span>, &#123;</span><br><span class="line">    <span class="attr">headers</span>: &#123; <span class="title class_">Accept</span>: <span class="string">&#x27;application/json&#x27;</span> &#125;,</span><br><span class="line">  &#125;);</span><br><span class="line">  <span class="keyword">return</span> (<span class="keyword">await</span> response.<span class="title function_">json</span>()) <span class="keyword">as</span> &#123;</span><br><span class="line">    <span class="attr">id</span>: <span class="built_in">string</span>;</span><br><span class="line">    <span class="attr">hitokoto</span>: <span class="built_in">number</span>;</span><br><span class="line">    <span class="attr">from</span>: <span class="built_in">string</span>;</span><br><span class="line">  &#125;;</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">const</span> useSentenceVoteAction = <span class="title function_">routeAction$</span>(<span class="function">(<span class="params">props</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;投票&#x27;</span>, props)</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> <span class="title function_">component$</span>(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">  <span class="comment">// 调用 `useHitokoto` 钩子, 会返回一个响应式信号量然后加载数据.</span></span><br><span class="line">  <span class="keyword">const</span> sentenceSignal = <span class="title function_">useHitokoto</span>();</span><br><span class="line">  <span class="keyword">const</span> favoriteSentenceAction = <span class="title function_">useSentenceVoteAction</span>();</span><br><span class="line">  <span class="keyword">const</span> isFavoriteSignal = <span class="title function_">useSignal</span>(<span class="literal">false</span>);</span><br><span class="line">  <span class="keyword">return</span> (</span><br><span class="line">    <span class="language-xml"><span class="tag">&lt;<span class="name">section</span> <span class="attr">class</span>=<span class="string">&quot;section bright&quot;</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">      <span class="tag">&lt;<span class="name">p</span>&gt;</span>&#123;sentenceSignal.value.hitokoto&#125; ——&#123;sentenceSignal.value.from&#125;<span class="tag">&lt;/<span class="name">p</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">      <span class="tag">&lt;<span class="name">Form</span> <span class="attr">action</span>=<span class="string">&#123;favoriteSentenceAction&#125;</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">        <span class="tag">&lt;<span class="name">input</span> <span class="attr">type</span>=<span class="string">&quot;hidden&quot;</span> <span class="attr">name</span>=<span class="string">&quot;id&quot;</span> <span class="attr">value</span>=<span class="string">&#123;sentenceSignal.value.id&#125;</span> /&gt;</span></span></span><br><span class="line"><span class="language-xml">        <span class="tag">&lt;<span class="name">input</span> <span class="attr">type</span>=<span class="string">&quot;hidden&quot;</span> <span class="attr">name</span>=<span class="string">&quot;sentence&quot;</span> <span class="attr">value</span>=<span class="string">&#123;sentenceSignal.value.hitokoto&#125;</span> /&gt;</span></span></span><br><span class="line"><span class="language-xml">        <span class="tag">&lt;<span class="name">button</span> <span class="attr">name</span>=<span class="string">&quot;vote&quot;</span> <span class="attr">value</span>=<span class="string">&quot;up&quot;</span>&gt;</span>👍<span class="tag">&lt;/<span class="name">button</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">        <span class="tag">&lt;<span class="name">button</span> <span class="attr">name</span>=<span class="string">&quot;vote&quot;</span> <span class="attr">value</span>=<span class="string">&quot;down&quot;</span>&gt;</span>👎<span class="tag">&lt;/<span class="name">button</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">      <span class="tag">&lt;/<span class="name">Form</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">      <span class="tag">&lt;<span class="name">button</span></span></span></span><br><span class="line"><span class="tag"><span class="language-xml">        <span class="attr">onClick</span>$=<span class="string">&#123;()</span> =&gt;</span> (isFavoriteSignal.value = !isFavoriteSignal.value)&#125;</span></span><br><span class="line"><span class="language-xml">      &gt;</span></span><br><span class="line"><span class="language-xml">        &#123;isFavoriteSignal.value ? &#x27;❤️&#x27; : &#x27;🤍&#x27;&#125;</span></span><br><span class="line"><span class="language-xml">      <span class="tag">&lt;/<span class="name">button</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">    <span class="tag">&lt;/<span class="name">section</span>&gt;</span></span></span><br><span class="line">  );</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<h3 id="监听状态变化并调用服务端函数"><a href="#监听状态变化并调用服务端函数" class="headerlink" title="监听状态变化并调用服务端函数"></a>监听状态变化并调用服务端函数</h3><p>在Qwik中，任务（task）是在状态发生变化时需要执行的工作（这类似于其他框架中的“effect”）。在本例中，我们使用任务来调用服务端上的代码。</p>
<ol>
<li>从 <code>qwik</code> 导入 <code>useTask$</code>: <code>import &#123; component$, useSignal, useTask$ &#125; from &quot;@builder.io/qwik&quot;;</code></li>
<li>创建一个task来监听isFavoriteSignal的状态变化：</li>
</ol>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="title function_">useTask$</span>(<span class="function">(<span class="params">&#123; track &#125;</span>) =&gt;</span> &#123; </span><br><span class="line">  <span class="title function_">track</span>(<span class="function">() =&gt;</span> isFavoriteSignal.<span class="property">value</span>);</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<ol start="3">
<li>添加要在状态更改时执行的代码：</li>
</ol>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="title function_">useTask$</span>(<span class="function">(<span class="params">&#123; track &#125;</span>) =&gt;</span> &#123; </span><br><span class="line">  <span class="title function_">track</span>(<span class="function">() =&gt;</span> isFavoriteSignal.<span class="property">value</span>);</span><br><span class="line">  <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;FAVORITE (isomorphic)&#x27;</span>, isFavoriteSignal.<span class="property">value</span>);</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<ol start="4">
<li>如果你希望在服务器上也进行执行某些代码，那么将这些封装在server$()中。</li>
</ol>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="title function_">useTask$</span>(<span class="function">(<span class="params">&#123; track &#125;</span>) =&gt;</span> &#123; </span><br><span class="line">  <span class="title function_">track</span>(<span class="function">() =&gt;</span> isFavoriteSignal.<span class="property">value</span>);</span><br><span class="line">  <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;FAVORITE (isomorphic)&#x27;</span>, isFavoriteSignal.<span class="property">value</span>);</span><br><span class="line">  <span class="title function_">server$</span>(<span class="function">() =&gt;</span> &#123; <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;FAVORITE (server)&#x27;</span>, isFavoriteSignal.<span class="property">value</span>); &#125;)();</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<p>最后代码变成：</p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> &#123; component$, useSignal, useTask$ &#125; <span class="keyword">from</span> <span class="string">&#x27;@builder.io/qwik&#x27;</span>;</span><br><span class="line"><span class="keyword">import</span> &#123; routeLoader$, <span class="title class_">Form</span>, routeAction$, server$ &#125; <span class="keyword">from</span> <span class="string">&#x27;@builder.io/qwik-city&#x27;</span>;</span><br><span class="line"> </span><br><span class="line"><span class="keyword">export</span> <span class="keyword">const</span> useHitokoto = <span class="title function_">routeLoader$</span>(<span class="keyword">async</span> () =&gt; &#123;</span><br><span class="line">  <span class="keyword">const</span> response = <span class="keyword">await</span> <span class="title function_">fetch</span>(<span class="string">&#x27;https://v1.hitokoto.cn/&#x27;</span>, &#123;</span><br><span class="line">    <span class="attr">headers</span>: &#123; <span class="title class_">Accept</span>: <span class="string">&#x27;application/json&#x27;</span> &#125;,</span><br><span class="line">  &#125;);</span><br><span class="line">  <span class="keyword">return</span> (<span class="keyword">await</span> response.<span class="title function_">json</span>()) <span class="keyword">as</span> &#123;</span><br><span class="line">    <span class="attr">id</span>: <span class="built_in">string</span>;</span><br><span class="line">    <span class="attr">hitokoto</span>: <span class="built_in">number</span>;</span><br><span class="line">    <span class="attr">from</span>: <span class="built_in">string</span>;</span><br><span class="line">  &#125;;</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">const</span> useSentenceVoteAction = <span class="title function_">routeAction$</span>(<span class="function">(<span class="params">props</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;投票&#x27;</span>, props)</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> <span class="title function_">component$</span>(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">  <span class="comment">// 调用 `useHitokoto` 钩子, 会返回一个响应式信号量然后加载数据.</span></span><br><span class="line">  <span class="keyword">const</span> sentenceSignal = <span class="title function_">useHitokoto</span>();</span><br><span class="line">  <span class="keyword">const</span> favoriteSentenceAction = <span class="title function_">useSentenceVoteAction</span>();</span><br><span class="line">  <span class="keyword">const</span> isFavoriteSignal = <span class="title function_">useSignal</span>(<span class="literal">false</span>);</span><br><span class="line">  <span class="title function_">useTask$</span>(<span class="function">(<span class="params">&#123; track &#125;</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="title function_">track</span>(<span class="function">() =&gt;</span> isFavoriteSignal.<span class="property">value</span>);</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;FAVORITE (isomorphic)&#x27;</span>, isFavoriteSignal.<span class="property">value</span>);</span><br><span class="line">    <span class="title function_">server$</span>(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">      <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;FAVORITE (server)&#x27;</span>, isFavoriteSignal.<span class="property">value</span>);</span><br><span class="line">    &#125;)();</span><br><span class="line">  &#125;);</span><br><span class="line">  <span class="keyword">return</span> (</span><br><span class="line">    <span class="language-xml"><span class="tag">&lt;<span class="name">section</span> <span class="attr">class</span>=<span class="string">&quot;section bright&quot;</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">      <span class="tag">&lt;<span class="name">p</span>&gt;</span>&#123;sentenceSignal.value.hitokoto&#125; ——&#123;sentenceSignal.value.from&#125;<span class="tag">&lt;/<span class="name">p</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">      <span class="tag">&lt;<span class="name">Form</span> <span class="attr">action</span>=<span class="string">&#123;favoriteSentenceAction&#125;</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">        <span class="tag">&lt;<span class="name">input</span> <span class="attr">type</span>=<span class="string">&quot;hidden&quot;</span> <span class="attr">name</span>=<span class="string">&quot;id&quot;</span> <span class="attr">value</span>=<span class="string">&#123;sentenceSignal.value.id&#125;</span> /&gt;</span></span></span><br><span class="line"><span class="language-xml">        <span class="tag">&lt;<span class="name">input</span> <span class="attr">type</span>=<span class="string">&quot;hidden&quot;</span> <span class="attr">name</span>=<span class="string">&quot;sentence&quot;</span> <span class="attr">value</span>=<span class="string">&#123;sentenceSignal.value.hitokoto&#125;</span> /&gt;</span></span></span><br><span class="line"><span class="language-xml">        <span class="tag">&lt;<span class="name">button</span> <span class="attr">name</span>=<span class="string">&quot;vote&quot;</span> <span class="attr">value</span>=<span class="string">&quot;up&quot;</span>&gt;</span>👍<span class="tag">&lt;/<span class="name">button</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">        <span class="tag">&lt;<span class="name">button</span> <span class="attr">name</span>=<span class="string">&quot;vote&quot;</span> <span class="attr">value</span>=<span class="string">&quot;down&quot;</span>&gt;</span>👎<span class="tag">&lt;/<span class="name">button</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">      <span class="tag">&lt;/<span class="name">Form</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">      <span class="tag">&lt;<span class="name">button</span></span></span></span><br><span class="line"><span class="tag"><span class="language-xml">        <span class="attr">onClick</span>$=<span class="string">&#123;()</span> =&gt;</span> (isFavoriteSignal.value = !isFavoriteSignal.value)&#125;</span></span><br><span class="line"><span class="language-xml">      &gt;</span></span><br><span class="line"><span class="language-xml">        &#123;isFavoriteSignal.value ? &#x27;❤️&#x27; : &#x27;🤍&#x27;&#125;</span></span><br><span class="line"><span class="language-xml">      <span class="tag">&lt;/<span class="name">button</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">    <span class="tag">&lt;/<span class="name">section</span>&gt;</span></span></span><br><span class="line">  );</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<img data-src="/%E5%89%8D%E7%AB%AF/QwikCourse-1/p4.png" class="">

<p>注意：</p>
<blockquote>
<p>组件中的<code>useTask$</code>会在服务端和客户端（浏览器）中执行一次。</p>
<p>当用户单击按钮时，浏览器会打印：<code>FAVORITE (isomorphic) true</code>，服务端打印：<code>FAVORITE (server) true</code></p>
</blockquote>
<h3 id="CSS样式"><a href="#CSS样式" class="headerlink" title="CSS样式"></a>CSS样式</h3><p>Qwik提供了一种将样式与组件关联并限定其范围的方法（类似Vue的scoped）。</p>
<ol>
<li>创建一个css文件，<code>src/routes/sentence/index.css</code>：</li>
</ol>
<figure class="highlight css"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="selector-tag">p</span> &#123;</span><br><span class="line">  <span class="attribute">font-weight</span>: bold;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="selector-tag">form</span> &#123;</span><br><span class="line">  <span class="attribute">float</span>: right;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ol start="2">
<li>导入样式：<code>import styles from &quot;./index.css?inline&quot;;</code></li>
<li>从qwik导入<code>useStylesScoped$</code>: <code>import &#123; component$, useSignal, useStylesScoped$, useTask$ &#125; from &quot;@builder.io/qwik&quot;;</code></li>
<li>告诉组件加载样式：<code>useStylesScoped$(styles);</code></li>
</ol>
<p>最后的代码：</p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> &#123; component$, useSignal, useTask$, useStylesScoped$ &#125; <span class="keyword">from</span> <span class="string">&#x27;@builder.io/qwik&#x27;</span>;</span><br><span class="line"><span class="keyword">import</span> &#123; routeLoader$, <span class="title class_">Form</span>, routeAction$, server$ &#125; <span class="keyword">from</span> <span class="string">&#x27;@builder.io/qwik-city&#x27;</span>;</span><br><span class="line"><span class="keyword">import</span> styles <span class="keyword">from</span> <span class="string">&#x27;./index.css?inline&#x27;</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">const</span> useHitokoto = <span class="title function_">routeLoader$</span>(<span class="keyword">async</span> () =&gt; &#123;</span><br><span class="line">  <span class="keyword">const</span> response = <span class="keyword">await</span> <span class="title function_">fetch</span>(<span class="string">&#x27;https://v1.hitokoto.cn/&#x27;</span>, &#123;</span><br><span class="line">    <span class="attr">headers</span>: &#123; <span class="title class_">Accept</span>: <span class="string">&#x27;application/json&#x27;</span> &#125;,</span><br><span class="line">  &#125;);</span><br><span class="line">  <span class="keyword">return</span> (<span class="keyword">await</span> response.<span class="title function_">json</span>()) <span class="keyword">as</span> &#123;</span><br><span class="line">    <span class="attr">id</span>: <span class="built_in">string</span>;</span><br><span class="line">    <span class="attr">hitokoto</span>: <span class="built_in">number</span>;</span><br><span class="line">    <span class="attr">from</span>: <span class="built_in">string</span>;</span><br><span class="line">  &#125;;</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">const</span> useSentenceVoteAction = <span class="title function_">routeAction$</span>(<span class="function">(<span class="params">props</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;投票&#x27;</span>, props)</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> <span class="title function_">component$</span>(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">  <span class="comment">// 调用 `useHitokoto` 钩子, 会返回一个响应式信号量然后加载数据.</span></span><br><span class="line">  <span class="keyword">const</span> sentenceSignal = <span class="title function_">useHitokoto</span>();</span><br><span class="line">  <span class="keyword">const</span> favoriteSentenceAction = <span class="title function_">useSentenceVoteAction</span>();</span><br><span class="line">  <span class="keyword">const</span> isFavoriteSignal = <span class="title function_">useSignal</span>(<span class="literal">false</span>);</span><br><span class="line">  <span class="title function_">useTask$</span>(<span class="function">(<span class="params">&#123; track &#125;</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="title function_">track</span>(<span class="function">() =&gt;</span> isFavoriteSignal.<span class="property">value</span>);</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;FAVORITE (isomorphic)&#x27;</span>, isFavoriteSignal.<span class="property">value</span>);</span><br><span class="line">    <span class="title function_">server$</span>(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">      <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;FAVORITE (server)&#x27;</span>, isFavoriteSignal.<span class="property">value</span>);</span><br><span class="line">    &#125;)();</span><br><span class="line">  &#125;);</span><br><span class="line">  <span class="title function_">useStylesScoped$</span>(styles)</span><br><span class="line">  <span class="keyword">return</span> (</span><br><span class="line">    <span class="language-xml"><span class="tag">&lt;<span class="name">section</span> <span class="attr">class</span>=<span class="string">&quot;section bright&quot;</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">      <span class="tag">&lt;<span class="name">p</span>&gt;</span>&#123;sentenceSignal.value.hitokoto&#125; ——&#123;sentenceSignal.value.from&#125;<span class="tag">&lt;/<span class="name">p</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">      <span class="tag">&lt;<span class="name">Form</span> <span class="attr">action</span>=<span class="string">&#123;favoriteSentenceAction&#125;</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">        <span class="tag">&lt;<span class="name">input</span> <span class="attr">type</span>=<span class="string">&quot;hidden&quot;</span> <span class="attr">name</span>=<span class="string">&quot;id&quot;</span> <span class="attr">value</span>=<span class="string">&#123;sentenceSignal.value.id&#125;</span> /&gt;</span></span></span><br><span class="line"><span class="language-xml">        <span class="tag">&lt;<span class="name">input</span> <span class="attr">type</span>=<span class="string">&quot;hidden&quot;</span> <span class="attr">name</span>=<span class="string">&quot;sentence&quot;</span> <span class="attr">value</span>=<span class="string">&#123;sentenceSignal.value.hitokoto&#125;</span> /&gt;</span></span></span><br><span class="line"><span class="language-xml">        <span class="tag">&lt;<span class="name">button</span> <span class="attr">name</span>=<span class="string">&quot;vote&quot;</span> <span class="attr">value</span>=<span class="string">&quot;up&quot;</span>&gt;</span>👍<span class="tag">&lt;/<span class="name">button</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">        <span class="tag">&lt;<span class="name">button</span> <span class="attr">name</span>=<span class="string">&quot;vote&quot;</span> <span class="attr">value</span>=<span class="string">&quot;down&quot;</span>&gt;</span>👎<span class="tag">&lt;/<span class="name">button</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">      <span class="tag">&lt;/<span class="name">Form</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">      <span class="tag">&lt;<span class="name">button</span></span></span></span><br><span class="line"><span class="tag"><span class="language-xml">        <span class="attr">onClick</span>$=<span class="string">&#123;()</span> =&gt;</span> (isFavoriteSignal.value = !isFavoriteSignal.value)&#125;</span></span><br><span class="line"><span class="language-xml">      &gt;</span></span><br><span class="line"><span class="language-xml">        &#123;isFavoriteSignal.value ? &#x27;❤️&#x27; : &#x27;🤍&#x27;&#125;</span></span><br><span class="line"><span class="language-xml">      <span class="tag">&lt;/<span class="name">button</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">    <span class="tag">&lt;/<span class="name">section</span>&gt;</span></span></span><br><span class="line">  );</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<p>效果：</p>
<img data-src="/%E5%89%8D%E7%AB%AF/QwikCourse-1/p5.png" class="">

<blockquote>
<p>上面就是Qwik官方文档的入门教程，有兴趣赶紧去试试吧</p>
</blockquote>

    </div>

    
    
    

    <footer class="post-footer">
          

<div class="post-copyright">
<ul>
  <li class="post-copyright-author">
      <strong>本文作者： </strong>Wyatex
  </li>
  <li class="post-copyright-link">
      <strong>本文链接：</strong>
      <a href="https://wyatex.online/%E5%89%8D%E7%AB%AF/QwikCourse-1/" title="Qwik官方入门教程（1）">https://wyatex.online/前端/QwikCourse-1/</a>
  </li>
  <li class="post-copyright-license">
      <strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh" rel="noopener" target="_blank"><i class="fab fa-fw fa-creative-commons"></i>BY-NC-SA</a> 许可协议。转载请注明出处！
  </li>
</ul>
</div>

          <div class="post-tags">
              <a href="/tags/%E5%89%8D%E7%AB%AF/" rel="tag"># 前端</a>
              <a href="/tags/%E6%95%99%E7%A8%8B/" rel="tag"># 教程</a>
              <a href="/tags/Qwik/" rel="tag"># Qwik</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/JavaScript/%E5%9B%9B%E7%A7%8D%E5%B8%B8%E8%A7%81%E7%9A%84%E4%BB%A3%E7%A0%81%E8%A6%86%E7%9B%96%E7%8E%87%E6%B5%8B%E8%AF%95/" rel="prev" title="四种常见的代码覆盖率测试">
                  <i class="fa fa-angle-left"></i> 四种常见的代码覆盖率测试
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/Flutter/FlutterCourse-1/" rel="next" title="面向Vue开发者的Flutter教程（1）">
                  面向Vue开发者的Flutter教程（1） <i class="fa fa-angle-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>






</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">

  <div class="copyright">
    &copy; 2019 – 
    <span itemprop="copyrightYear">2024</span>
    <span class="with-love">
      <i class="fa fa-heart"></i>
    </span>
    <span class="author" itemprop="copyrightHolder">Wyatex</span>
  </div>
<div class="busuanzi-count">
    <span class="post-meta-item" id="busuanzi_container_site_uv">
      <span class="post-meta-item-icon">
        <i class="fa fa-user"></i>
      </span>
      <span class="site-uv" title="总访客量">
        <span id="busuanzi_value_site_uv"></span>
      </span>
    </span>
    <span class="post-meta-item" id="busuanzi_container_site_pv">
      <span class="post-meta-item-icon">
        <i class="fa fa-eye"></i>
      </span>
      <span class="site-pv" title="总访问量">
        <span id="busuanzi_value_site_pv"></span>
      </span>
    </span>
</div>

    </div>
  </footer>

  
  <div class="back-to-top" role="button" aria-label="返回顶部">
    <i class="fa fa-arrow-up fa-lg"></i>
    <span>0%</span>
  </div>
  <div class="reading-progress-bar"></div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


  
  <script size="300" alpha="0.6" zIndex="-1" src="/lib/ribbon.js/dist/ribbon.min.js"></script>
  <script src="/lib/animejs/lib/anime.min.js" integrity="sha256-XL2inqUJaslATFnHdJOi9GfQ60on8Wx1C2H8DYiN1xY=" crossorigin="anonymous"></script>
  <script src="/lib/@next-theme/pjax/pjax.min.js" integrity="sha256-vxLn1tSKWD4dqbMRyv940UYw4sXgMtYcK6reefzZrao=" crossorigin="anonymous"></script>
  <script src="/lib/@fancyapps/ui/dist/fancybox/fancybox.umd.js" integrity="sha256-q8XkJ6dj5VwSvzI8+nATCHHQG+Xv/dAZBCgqmu93zOY=" crossorigin="anonymous"></script>
  <script src="/lib/lozad/dist/lozad.min.js" integrity="sha256-mOFREFhqmHeQbXpK2lp4nA3qooVgACfh88fpJftLBbc=" crossorigin="anonymous"></script>
<script src="/js/comments.js"></script><script src="/js/utils.js"></script><script src="/js/motion.js"></script><script src="/js/next-boot.js"></script><script src="/js/pjax.js"></script>

  <script src="/lib/hexo-generator-searchdb/dist/search.js" integrity="sha256-1kfA5uHPf65M5cphT2dvymhkuyHPQp5A53EGZOnOLmc=" crossorigin="anonymous"></script>
<script src="/js/third-party/search/local-search.js"></script>




  <script src="/js/third-party/fancybox.js"></script>



  
  <script data-pjax async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>





</body>
</html>
